#include <QFileInfo>
#include <QDir>
#include "ModuleScope.h"
#include "ast/Import.h"
#include "../ModulesMgr.h"
#include "FunctionScope.h"
#include "ClassScope.h"


ModuleScope::ModuleScope(const ModulePtr& moduleAst, const QFileInfo& fileName):
    Scope(NULL),
    _moduleAst(moduleAst),
    _fileName(fileName)
{
    //buildScope();
}

ModuleScope::~ModuleScope()
{

}

void ModuleScope::buildScope()
{
    visitModule(_moduleAst);
    //qDebug() << _names.keys();
}

void ModuleScope::visitModule(const ModulePtr &node)
{
     node->traverse(this);
}

void ModuleScope::visitImport(const ImportPtr &node)
{
    foreach(aliasTypePtr alias, node->names()){
        ModuleScope *mod = ModulesMgr::instance().moduleByName(alias->name()->id(), _fileName.absolutePath());
        if (alias->asname() && !alias->asname()->id().isEmpty())
            _names[alias->asname()->id()] = mod;
        else
            _names[alias->name()->id()] = mod;
    }
}

void ModuleScope::visitImportFrom(const ImportFromPtr &node)
{
    ModuleScope *mod = ModulesMgr::instance().moduleByName(node->module()->id(), _fileName.absolutePath());
    if (!mod)
        return;

    if (!node->names().length()){
        // import *
        //TODO: warning, import *
        foreach(QString name, mod->_names.keys()){
            _names[name] = mod->_names[name];
        }
    } else {
        foreach(aliasTypePtr alias, node->names()){
            //qDebug() << alias->name()->id();
            if (mod->_names.contains(alias->name()->id()))
                _names[alias->name()->id()] = mod->_names[alias->name()->id()];
        }
    }
}

void ModuleScope::visitFunctionDef(const FunctionDefPtr &node)
{
    FunctionScope * fnc = new FunctionScope(node, this);
    _names[node->name()->id()] = fnc;
    _childScopes.append(fnc);
}

void ModuleScope::visitClassDef(const ClassDefPtr &node)
{
    ClassScope *cls = new ClassScope(node, this);
    _names[node->name()->id()] = cls;
    _childScopes.append(cls);
}
